package com.snowdragon.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snowdragon.common.core.constants.HttpConstants;
import com.snowdragon.common.core.domain.po.LoginUser;
import com.snowdragon.common.core.domain.po.R;
import com.snowdragon.common.core.domain.vo.LoginUserVO;
import com.snowdragon.common.core.enums.ResultCode;
import com.snowdragon.common.core.enums.UserIdentity;
import com.snowdragon.common.security.exception.ServiceException;
import com.snowdragon.common.security.service.TokenService;
import com.snowdragon.system.domain.sysuser.dto.SysUserSaveDTO;
import com.snowdragon.system.domain.sysuser.po.SysUser;
import com.snowdragon.system.mapper.SysUserMapper;
import com.snowdragon.system.service.sysuser.ISysUserService;
import com.snowdragon.system.utils.BCryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public R<String> login(SysUserSaveDTO sysUserSaveDTO) {
        String userAccount = sysUserSaveDTO.getUserAccount();
        String password = sysUserSaveDTO.getPassword();
        SysUser sysUser = lambdaQuery()
                .eq(SysUser::getUserAccount, userAccount).one();
        if(sysUser == null) {
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            log.info("密码校验正确");
//            return R.ok("成功");
            return R.ok(tokenService.createToken(sysUser.getUserId(), secret,
                    UserIdentity.ADMIN.getValue(), sysUser.getNickName(), null));
        }
        return R.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public boolean add(SysUserSaveDTO sysUserSaveDTO) {
        List<SysUser> sysUsers = lambdaQuery().eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()).list();
        if (CollectionUtil.isNotEmpty(sysUsers)) {
            //用户已经存在
            //自定义的异常   公共的异常类
            throw new ServiceException(ResultCode.FAILED_USER_EXISTS);
        }
        SysUser user = SysUser.builder()
                .userAccount(sysUserSaveDTO.getUserAccount())
                .password(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()))
//                .nickName(null)
                .build();
        user.setCreateBy(1L);
        return save(user);
    }

    @Override
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
//        removeTokenPre(token);
        return tokenService.deleteLoginUser(token, secret);
    }

    @Override
    public R<LoginUserVO> info(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
//        removeTokenPre(token);
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if (loginUser == null) {
            return R.fail();
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return R.ok(loginUserVO);
    }

//    private void removeTokenPre(String token) {
//        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
//            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
//        }
//    }
}
